package com.nercel.dsj.gksales.api.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.nercel.dsj.gksales.model.ListResult;
import com.nercel.dsj.gksales.model.QueryParams;
import com.nercel.dsj.gksales.model.ResponseResult;
import com.nercel.dsj.gksales.model.dto.SalesRecordResultDTO;
import com.nercel.dsj.gksales.model.entity.SellRecord;
import com.nercel.dsj.gksales.service.ExportService;
import com.nercel.dsj.gksales.service.SellRecordService;
import com.nercel.dsj.gksales.util.ApiResultUtil;
import com.nercel.dsj.gksales.util.DateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;

@RestController
@Api(tags = "销售记录")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SellRecordApiController extends BaseApiController {

    private final SellRecordService sellRecordService;

    private final ExportService exportService;

    @ApiOperation(value = "记录查询接口")
    @RequestMapping(value = "/api/v1/sales", method = RequestMethod.GET)
    public ListResult<SalesRecordResultDTO> query(@ApiParam(hidden = true) QueryParams queryParams,
        @ApiParam(value = "页码") @RequestParam(required = false) Integer page,
        @ApiParam(value = "单页数量") @RequestParam(required = false) Integer pageSize,
        @ApiParam(value = "备注关键词") @RequestParam(required = false) String keyword,
        @ApiParam(value = "支付类型(微信1 支付宝2 沃3)") @RequestParam(required = false) Integer payType,
        @ApiParam(value = "销售员ID") @RequestParam(required = false) Integer userId,
        @ApiParam(value = "客户手机号") @RequestParam(required = false) String customerPhone,
        @ApiParam(value = "排序类型 1: ID倒序 2:按用户排序") @RequestParam(required = false, defaultValue = "2") Integer orderType,
        @ApiParam(value = "客户ID") @RequestParam(required = false) Integer customerId,
        @ApiParam(value = "区域ID（查询区域下所有记录）") @RequestParam(required = false) Integer topRegionId,
        @ApiParam(value = "新建的帐号") @RequestParam(required = false) Boolean newCreated,
        @ApiParam(value = "开始时间") @RequestParam(required = false) String timeBegin,
        @ApiParam(value = "结束时间") @RequestParam(required = false) String timeEnd) {
        queryParams.put("keyword", keyword);
        queryParams.put("payType", payType);
        queryParams.put("userId", userId);
        queryParams.put("customerPhone", customerPhone);
        queryParams.put("customerId", customerId);
        queryParams.put("topRegionId", topRegionId);
        queryParams.put("newCreated", newCreated);
        queryParams.put("timeBegin", timeBegin);
        queryParams.put("timeEnd", timeEnd);
        queryParams.put("orderType", orderType);
        return sellRecordService.listWithPaging(queryParams);
    }

    @ApiOperation(value = "记录查询导出")
    @RequestMapping(value = "/api/v1/sales/export", method = RequestMethod.GET)
    public ResponseResult export(@ApiParam(hidden = true) QueryParams queryParams,
        @ApiParam(value = "页码") @RequestParam(required = false) Integer page,
        @ApiParam(value = "单页数量") @RequestParam(required = false) Integer pageSize,
        @ApiParam(value = "备注关键词") @RequestParam(required = false) String keyword,
        @ApiParam(value = "支付类型(微信1 支付宝2 沃3)") @RequestParam(required = false) Integer payType,
        @ApiParam(value = "销售员ID") @RequestParam(required = false) Integer userId,
        @ApiParam(value = "排序类型 1: ID倒序 2:按用户排序") @RequestParam(required = false, defaultValue = "1") Integer orderType,
        @ApiParam(value = "客户手机号") @RequestParam(required = false) String customerPhone,
        @ApiParam(value = "客户ID") @RequestParam(required = false) Integer customerId,
        @ApiParam(value = "区域ID（查询区域下所有记录）") @RequestParam(required = false) Integer topRegionId,
        @ApiParam(value = "新建的帐号") @RequestParam(required = false) Boolean newCreated,
        @ApiParam(value = "开始时间") @RequestParam(required = false) String timeBegin,
        @ApiParam(value = "结束时间") @RequestParam(required = false) String timeEnd) {
        queryParams.put("keyword", keyword);
        queryParams.put("payType", payType);
        queryParams.put("userId", userId);
        queryParams.put("customerPhone", customerPhone);
        queryParams.put("customerId", customerId);
        queryParams.put("topRegionId", topRegionId);
        queryParams.put("newCreated", newCreated);
        queryParams.put("orderType", orderType);
        queryParams.put("timeBegin", timeBegin);
        queryParams.put("timeEnd", timeEnd);
        List<SalesRecordResultDTO> list = sellRecordService.list(queryParams);
        List<List<String>> data = new ArrayList<>();
        List<String> hd = new ArrayList<>();
        hd.add("订单ID");
        hd.add("省分");
        hd.add("地市");
        hd.add("区县");
        hd.add("渠道名称");
        hd.add("渠道编码");
        hd.add("员工姓名");
        hd.add("员工身份证号");
        hd.add("员工编码");
        hd.add("员工开通工号");
        hd.add("员工开户行");
        hd.add("员工银行卡号");
        hd.add("产品名称");
        hd.add("产品编码");
        hd.add("用户开通号码");
        hd.add("用户姓名");
        hd.add("受理时间");
        hd.add("开通时间");
        hd.add("营业受理金额");
        hd.add("收款类型");
        hd.add("支付凭证");
        data.add(hd);
        list.forEach(it -> {
            List<String> item = new ArrayList<>();
            item.add(it.getId().toString());
            item.add(it.getProvince());
            item.add(it.getCity());
            item.add(it.getCounty());
            item.add(it.getChannelName());
            item.add(it.getChannelNumber());
            item.add(it.getName());
            item.add(it.getIdNumber());
            item.add(it.getUserNumber());
            item.add(it.getPhone());
            item.add(it.getBankInfo());
            item.add(it.getBankAccount());
            item.add("高考U选");
            item.add("GKVIP");
            item.add(it.getCustomerPhone());
            item.add(it.getCustomerName());
            item.add(it.getCreateTime() == null ? "" : DateUtil.getTime(it.getCreateTime()));
            item.add(it.getCreateTime() == null ? "" : DateUtil.getTime(it.getCreateTime()));
            item.add(it.getAmount() == null ? "" : String.valueOf(Double.valueOf(it.getAmount()) / 100));
            item.add(getPayTypeName(it.getPayType()));
            item.add(it.getPayPhoto());
            data.add(item);
        });
        String filename = exportService.export(ExportService.BLANK_TPL, "销售记录明细", data, 0);
        return ApiResultUtil.success(filename);
    }

    public static String getPayTypeName(Integer type) {
        if (type == null) {
            return "";
        }
        String[] types = new String[] {"", "微信", "支付宝", "二合一", "在线支付宝", "在线微信"};
        return types[type];
    }

    @PostMapping(value = "/api/v1/sales")
    @ApiOperation(value = "销售VIP")
    public ResponseResult sell(@RequestBody SellRecord params) {
        Integer userId = getUserId(); // 当前登陆的用户（销售人员）
        params.setUserId(getUserId());
        params.setCreateTime(new Date());
        sellRecordService.saveAndActivate(params, userId);
        return ApiResultUtil.success();
    }

    @PostMapping(value = "/api/v1/sales/batch")
    @ApiOperation(value = "批量销售VIP")
    public ResponseResult sellBatch(@RequestBody List<SellRecord> params) {
        Integer userId = getUserId(); // 当前登陆的用户（销售人员）
        sellRecordService.saveAndActivateBatch(params, userId);
        return ApiResultUtil.success();
    }

    //
    // @ApiOperation(value = "代理分布统计")
    // @GetMapping(value="/api/v1/agents/statistics")
    // public List<Map<String, Object>> statistics(
    // @ApiParam(hidden = true) QueryParams queryParams,
    // @ApiParam(value = "区域ID") @RequestParam(required = false) Integer topRegionId,
    // @ApiParam(value = "统计级别 1省 2市 3区") @RequestParam(required = false, defaultValue = "1") Integer level
    // ){
    // queryParams.put("level", level);
    // queryParams.put("topRegionId", topRegionId);
    // return agentService.statistics(queryParams);
    // }

    @ApiOperation(value = "销售量统计")
    @GetMapping(value = "/api/v1/sales/records/statistics")
    public List<Map<String, Object>> salesRecordsStatistics(@ApiParam(hidden = true) QueryParams queryParams,
        @ApiParam(value = "区域ID") @RequestParam(required = false) Integer topRegionId,
        @ApiParam(value = "统计级别 1省 2市 3销售") @RequestParam(required = false, defaultValue = "1") Integer level,
        @ApiParam(value = "开始时间") @RequestParam(required = false) String timeBegin,
        @ApiParam(value = "结束时间") @RequestParam(required = false) String timeEnd) {
        queryParams.put("level", level);
        queryParams.put("topRegionId", topRegionId);
        queryParams.put("timeBegin", timeBegin);
        queryParams.put("timeEnd", timeEnd);
        return sellRecordService.salesRecordsStatistics(queryParams);
    }

}
